package com.example.demo.test001;

import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Json4Excel {


    private static final Gson gson = new Gson();
    private static final String SUFFIX_2003 = ".xls";
    private static final String SUFFIX_2007 = ".xlsx";

    public static void main(String[] args) {

    }
    public static String jsonToExcel(String json ,String excelType){
        if(StringUtils.isEmpty(json)){
            return null;
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        List<Map<String,String>> jsonList = gson.fromJson(json, List.class);
        HSSFSheet sheet = workbook.createSheet("疫情信息");
        if(jsonList==null || jsonList.isEmpty()){
            return  null;
        }

        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        Map<String,String> headersMap = jsonList.get(0);
        // 表头
        Set<String> headerSet = headersMap.keySet();
        List<String> headers = new ArrayList<>(headerSet);
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for(int i=0;i<headers.size();i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers.get(i));
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (int i=0;i<jsonList.size();i++) {
            Map<String,String> map = jsonList.get(i);
            HSSFRow row1 = sheet.createRow(rowNum);
            for (int j = 0; j < headers.size(); j++) {
                row1.createCell(j).setCellValue(map.get(headers.get(j)));
            }
            rowNum++;
        }

        try {
            String filePath = PropertiesUtils.getPropertiesByKey("jsonOutFilePath")+
                    new SimpleDateFormat("yyyyMMdd-HH-mm-ss").format(new Date()) +SUFFIX_2003;
            workbook.write(new FileOutputStream(new File(filePath)));
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
